// 自定义判断元素类型
const toType = (obj) => {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

// 如果是null、undefined或者空字符串则为空
const isBlank = (value) => {
  return (
    value === undefined ||
    value === null ||
    (toType(value) === 'string' && value.trim() === '')
  )
}

// 过滤FormData
const filterFormData = (data) => {
  let sign = false
  const formData = new FormData()
  for (const [key, value] of data.entries()) {
    const newValue = filterData(value)
    if (!isBlank(newValue)) {
      formData.append(key, filterData(value))
      sign = true
    }
  }
  return sign ? formData : undefined
}

// 过滤数组
const filterArray = (data) => {
  let sign = false
  const array = []
  for (const value of data) {
    const newValue = filterData(value)
    if (!isBlank(newValue)) {
      array.push(newValue)
      sign = true
    }
  }
  return sign ? array : undefined
}

// 过滤对象
const filterObject = (data) => {
  let sign = false
  const object = {}
  for (const [key, value] of Object.entries(data)) {
    const newValue = filterData(value)
    if (!isBlank(newValue)) {
      object[key] = filterData(value)
      sign = true
    }
  }
  return sign ? object : undefined
}

// 参数过滤函数
const filterData = (data) => {
  // 过滤空数据
  if (isBlank(data)) {
    return undefined
  }
  // 非空数据
  switch (toType(data)) {
    // 字符串
    case 'string': return data.trim()
    // FormData
    case 'formdata': return filterFormData(data)
    // 数组
    case 'array': return filterArray(data)
    // 普通对象
    case 'object': return filterObject(data)
    // 其他
    default: return data
  }
}

export {
  toType,
  isBlank,
  filterData
}
